<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\ArticleColumn;
use App\Model\Collect;
use App\Model\MultiCollect;
use App\Model\MultiLearn;
use App\Model\MultiZan;
use App\Model\News;
use App\Model\Notify;
use App\Model\Study;
use App\Model\StudyColumn;
use App\Model\StudyColumnCategory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class StudyController extends AppBaseController
{

    /**
     * 学习天地首页信息
     * @return object
     */
    #[RequestMapping(path:'studyData',methods: 'get')]
    public function studyData(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $whereBanner['status'] = 1;
            $whereBanner['is_banner'] = 1;
            $bannerList = Study::where($whereBanner)
                ->selectRaw('id,type,title,photo,banner_photo,file_list,link_url,created_at')
                ->get();

            //获取专栏
            $specialColumnList = ArticleColumn::where(['type'=>1,'is_banner'=>1])
                ->selectRaw('id,name,is_banner,banner_photo,created_at')
                ->get();

            //学习天地分类 1：学习理论 2：党建文件 3：廉政教育
            $where['status'] = 1;
            $where['is_show'] = 1;
            $where['column_id'] = 1; //学习理论
            $column1List = Study::where($where)
                ->selectRaw('id,type,title,photo,file_list,link_url,created_at')
                ->get();

            //先获取党建文件小分类
            $column2CateList = StudyColumnCategory::where('column_id',2)
                ->selectRaw('id,name')
                ->get();
            $column_cate_id = 0;
            if($column2CateList->isNotEmpty()){
                foreach ($column2CateList as $key=>$value){
                    $column_cate_id = $value->id;
                    break;
                }
            }
            //党建文件 -- 小分类
            if($column_cate_id>0){
                $where['column_cate_id'] = $column_cate_id;
            }
            $where['column_id'] = 2; //党建文件
            $column2List = Study::where($where)
                ->selectRaw('id,type,title,photo,file_list,link_url,created_at')
                ->get();

            $where['column_id'] = 3; //廉政教育
            $column3List = Study::where($where)
                ->selectRaw('id,type,title,photo,file_list,link_url,created_at')
                ->get();

            return $this->reMsg->re(1,'success',[
                'banner_ist'=>$bannerList,
                'special_column_list'=>$specialColumnList,
                'column1_list' => $column1List,
                'column2_cate_list'=>$column2CateList,
                'column2_list' => $column2List,
                'column3_list' => $column3List
            ]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 学习天地列表
     * @param int $column_id  0:全部 1：理论学习 2：党建文件 3：廉政教育
     * @return object
     */
    #[RequestMapping(path:'studyList[/{column_id}]',methods: 'get')]
    public function studyList(int $column_id = 0): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            
            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $column_cate_id = $this->request->input('column_cate_id', null);

            //小分类
            if($column_cate_id){
                $where['column_cate_id'] = $column_cate_id;
            }

            $where['status'] = 1;

            if(is_numeric($column_id) && $column_id!=0){
                $where['column_id'] = $column_id;
            }
            $where['is_long'] = 1;

            $dateTime = date('Y-m-d H:i:s',time());
            if($column_cate_id){
                $where['column_cate_id'] = $column_cate_id;
                $whereOr = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['column_cate_id','=',$column_cate_id],
                    ['show_start_at','<=',$dateTime],
                    ['show_end_at','>=',$dateTime],
                ];
            }else{
                $whereOr = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['show_start_at','<=',$dateTime],
                    ['show_end_at','>=',$dateTime],
                ];
            }
            $list = Study::where($where)
                ->orWhere($whereOr)
                ->selectRaw('id,title,type,photo,media_list,file_list,link_url,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    
    /**
     * 首页-党建文件（单独）
     * @return object
     */
    #[RequestMapping(path:'studyDjList',methods: 'get')]
    public function studyDjList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $column_id = 2;  //党建问价是2

            //获取党建文件小分类
            $categoryWhere['status'] = 1;
            $categoryWhere['column_id'] = $column_id;

            $columnCategoryList = StudyColumnCategory::where($categoryWhere)->selectRaw('id,column_id,name')->get();
            if($columnCategoryList->isEmpty()) return $this->reMsg->re(1,'success',[
                'column_cate_list' => $columnCategoryList
            ]);


            foreach ($columnCategoryList as $key=>$value) {
                $where = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['column_cate_id','=',$value->id],
                    ['is_long','=',1],
                ];

                $dateTime = date('Y-m-d H:i:s',time());
                $whereOr = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['column_cate_id','=',$value->id],
                    ['show_start_at','<=',$dateTime],
                    ['show_end_at','>=',$dateTime],
                ];

                $value->study = Study::where($where)
                    ->orWhere($whereOr)
                    ->selectRaw('id,title,type,column_cate_id,photo,file_list,link_url,created_at')
                    ->orderByDesc('id')
                    ->limit(3)
                    ->get();
            }
            return $this->reMsg->re(1,'success',[
                'column_cate_list' => $columnCategoryList
            ]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 学习天地首页-新接口
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'studyNewList/{column_id}',methods: 'get')]
    public function studyNewList(int $column_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            if(!in_array($column_id,[1,2,3])) return $this->reMsg->re(10007);

            //获取党建文件小分类
            $categoryWhere['status'] = 1;
            $categoryWhere['column_id'] = $column_id;

            $columnCategoryList = StudyColumnCategory::where($categoryWhere)->selectRaw('id,column_id,name')->get();
            if($columnCategoryList->isEmpty()) return $this->reMsg->re(1,'success',[
                'column_cate_list' => $columnCategoryList
            ]);


            foreach ($columnCategoryList as $key=>$value) {
                $where = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['column_cate_id','=',$value->id],
                    ['is_long','=',1],
                ];

                $dateTime = date('Y-m-d H:i:s',time());
                $whereOr = [
                    ['status','=',1],
                    ['column_id','=',$column_id],
                    ['column_cate_id','=',$value->id],
                    ['show_start_at','<=',$dateTime],
                    ['show_end_at','>=',$dateTime],
                ];

                $value->study = Study::where($where)
                    ->orWhere($whereOr)
                    ->selectRaw('id,title,type,column_cate_id,photo,media_list,file_list,link_url,created_at')
                    ->orderByDesc('id')
                    ->limit(3)
                    ->get();
            }
            return $this->reMsg->re(1,'success',[
                'column_cate_list' => $columnCategoryList
            ]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 学习天地详情
     * @param int $study_id
     * @return object
     */
    #[RequestMapping(path:'studyInfo/{study_id}',methods: 'get')]
    public function studyInfo(int $study_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];
            
            $info = Study::where('id',$study_id)
                ->selectRaw('id,column_id,column_cate_id,type,title,photo,content,media_list,file_list,created_at')
                ->first();
            if(empty($info)) return $this->reMsg->re(10008);

            $info->is_collect = 0;
            $info->is_learn = 0;
            $info->is_zan = 0;
            //处理用户是否收藏
            $whereDo['module'] = 'study';
            $whereDo['relation_id'] = $info->id;

            //获取点赞数量
            $info->zan_count = MultiZan::where($whereDo)->count();

            $whereDo['uid'] = $_user->id;
            //判断是否学习
            $learnInfo = MultiLearn::where($whereDo)->first();
            if($learnInfo) $info->is_learn = 1;
            //判断是否收藏
            $whereDo['status'] = 1;
            $collectInfo = MultiCollect::where($whereDo)->first();
            if($collectInfo) $info->is_collect = 1;
            //判断是否点赞
            $zanInfo = MultiZan::where($whereDo)->first();
            if($zanInfo) $info->is_zan = 1;


            //处理用户的[消息通知-》学习天地]为已处理
            $newsWhere['type'] = 4;
            $newsWhere['link_id'] = $study_id;
            $newsInfo = News::where($newsWhere)->first();
            if($newsInfo){
                //处理消息
                $where['module'] = 1;
                $where['relation_id'] = $newsInfo->id;
                $where['uid'] = $_user->id;
                $notifyInfo = Notify::where($where)->first();
                if($notifyInfo && $notifyInfo->status==0){
                    $notifyInfo->status = 1;
                    $notifyInfo->save();
                }
            }
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



}